package yxy.game.pm2.command.chibi;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ChibiMessage;
import yxy.game.pm2.module.chibi.RankChibi;
import yxy.game.pm2.module.player.PlayerHandle;

import java.util.Collection;

/** 火烧赤壁 火烧赤壁排行榜 */
@MessageType(proto = Command.ChibiRank, classtype = ChibiMessage.ChibiRankRequest.class)
public class CMD_ChibiRank extends Command<ChibiMessage.ChibiRankRequest> {

	@Override
	public void execute(MessageSource messageSource, ChibiMessage.ChibiRankRequest request) {
		String playerCode = messageSource.getTag();

		ChibiMessage.ChibiRankResponse.Builder response = ChibiMessage.ChibiRankResponse.newBuilder();

		RankChibi rankChibi = RankChibi.getRank(playerCode);
		try {
			PlayerHandle playerHandle = new PlayerHandle();
			Collection<RankEntry> top = rankChibi.top(rankChibi.topSize());
			int rank = 0;

			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int score = entry.getValue().intValue();

				ChibiMessage.RankChibi.Builder builder = ChibiMessage.RankChibi.newBuilder();

				builder.setRank(++rank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(pCode));
				builder.setScore(score);
				response.addRank(builder);
			}
			{
				int playerRank = 0;
				int score = 0;
				RankEntry entry = rankChibi.get(playerCode);
				if (entry != null) {
					playerRank = rankChibi.rank(playerCode);
					score = entry.getValue().intValue();
				}

				ChibiMessage.RankChibi.Builder builder = ChibiMessage.RankChibi.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(playerCode));
				builder.setScore(score);
				response.setMy(builder);
			}

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, ChibiMessage.ChibiRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}